<template>
  <div class="favorite-management">
    <h2>我的收藏</h2>
    <table>
      <thead>
        <tr>
          <th>用户名</th>
          <th>文章标题</th>
          <th>收藏时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="favorite in paginatedFavorites" :key="favorite.post_id">
          <td>{{ favorite.username }}</td>
          <td>
            <router-link 
              :to="`/article/detail/${favorite.post_id}`" 
              class="article-title"
            >
              {{ favorite.post_title }}
            </router-link>
          </td>
          <td>{{ formatDate(favorite.created_at) }}</td>
          <td>
            <button @click="viewArticleDetails(favorite.post_id)" class="view-btn">查看</button>
            <button @click="removeFavorite(favorite.post_id)" class="delete-btn">取消收藏</button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 无数据时显示 -->
    <div v-if="favorites.length === 0" class="no-data">
      暂无收藏文章
    </div>

    <!-- 分页组件 -->
    <el-pagination
      v-if="favorites.length > 0"
      background
      layout="prev, pager, next"
      :total="favorites.length"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />

    <!-- 确认删除弹窗 -->
    <el-dialog
      title="确认取消"
      v-model="showDeleteModal"
      width="30%"
      center
    >
      <span>确定要取消收藏该文章吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelRemove">取消</el-button>
          <el-button type="primary" @click="confirmRemove">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      favorites: [],
      showDeleteModal: false,
      deletePostId: null,
      currentPage: 1,
      pageSize: 10, // 增加每页显示数量
      loading: false, // 添加加载状态
    };
  },
  computed: {
    paginatedFavorites() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.favorites.slice(start, start + this.pageSize);
    },
  },
  created() {
    this.loadFavorites();
  },
  methods: {
    async loadFavorites() {
      this.loading = true;
      try {
        const token = localStorage.getItem("token");
        if (!token) {
          this.$message.error("用户未登录，请先登录！");
          this.$router.push('/login');
          return;
        }

        const response = await axios.get("http://localhost:9090/favorites", {
          headers: { Authorization: `${token}` },
        });

        this.favorites = response.data.favorites;
      } catch (error) {
        console.error("加载收藏列表失败", error);
        this.$message.error("加载收藏列表失败，请检查登录状态！");
      } finally {
        this.loading = false;
      }
    },
    handlePageChange(newPage) {
      this.currentPage = newPage;
    },
    viewArticleDetails(id) {
      this.$router.push(`/article/detail/${id}`);
    },
    removeFavorite(postId) {
      this.showDeleteModal = true;
      this.deletePostId = postId;
    },
    async confirmRemove() {
      try {
        await axios.delete(`http://localhost:9090/favorite/${this.deletePostId}`);
        this.favorites = this.favorites.filter(fav => fav.post_id !== this.deletePostId);
        this.$message.success("取消收藏成功");
        this.cancelRemove();
      } catch (error) {
        console.error("取消收藏失败", error);
        this.$message.error("取消收藏失败");
      }
    },
    cancelRemove() {
      this.showDeleteModal = false;
      this.deletePostId = null;
    },
    formatDate(dateString) {
      return new Date(dateString).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
  },
};
</script>

<style scoped>
.favorite-management {
  width: 80%;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.article-title {
  color: #409EFF;
  text-decoration: none;
}

.article-title:hover {
  text-decoration: underline;
}

.view-btn, .delete-btn {
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  margin-right: 10px;
  border: none;
  cursor: pointer;
}

.view-btn {
  background-color: #409EFF;
  color: white;
}

.delete-btn {
  background-color: #F56C6C;
  color: white;
}

.view-btn:hover {
  background-color: #66b1ff;
}

.delete-btn:hover {
  background-color: #f78989;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}

/* 分页样式优化 */
.el-pagination {
  margin-top: 30px;
  text-align: center;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 20px;
}
</style>